package com.yuyou.fn.updater.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.google.common.base.Optional;
import com.google.common.cache.LoadingCache;
import com.yuyou.fn.common.database.event.EventHandler;
import com.yuyou.fn.common.database.event.IEventHandler;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.crm.entity.CrmStudentCommunicate;
import com.yuyou.fn.crm.entity.CustomerResource;
import com.yuyou.fn.crm.service.ICrmStudentCommunicateService;
import com.yuyou.fn.crm.service.ICustomerResourceService;
import com.yuyou.fn.crm.vo.CrmStudentCommunicateQueryVo;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.platform.entity.BusTeam;
import com.yuyou.fn.platform.service.IBusTeamService;
import com.yuyou.fn.report.entity.MergeStudentRegDetail;
import com.yuyou.fn.report.entity.StudentRegDetail;
import com.yuyou.fn.report.service.IMergeStudentRegDetailService;
import com.yuyou.fn.report.service.IStudentRegDetailService;
import com.yuyou.fn.settlement.entity.PayRecord;
import com.yuyou.fn.settlement.service.IPayRecordService;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutionException;

@EventHandler(tables = {"yyfn.student_reg"})
@Component
public class CrmResourceRegCountUpdater implements IEventHandler {

    private final static Logger log = LoggerFactory.getLogger(CrmResourceRegCountUpdater.class);

    @Resource
    private IStudentRegService studentRegService;

    @Resource
    private ICourseOrderService courseOrderService;

    @Resource
    private IStudentService studentService;

    @Resource
    private ICustomerResourceService customerResourceService;




    private LoadingCache<Long,Optional<Student>> loadingCacheOfStudent;

    @PostConstruct
    public void init(){

        this.loadingCacheOfStudent = CacheUtils.buildCache(studentService::findById);

    }


    private static String[] classColumns={"classId","className","courseTemplateId","gradeId","gradeName","subjectId","subjectName","lectureAmount","studyingFee","periodId","periodName","areaTeamId","areaTeamName","busTeamId","busTeamName","campusId","campusName","productId"};


    @Override
    public void insert(String tableName, JSONArray rowList) {
        build(tableName, rowList);
    }

    @Override
    public void update(String tableName, JSONArray rowList, Set<String> updateColumns) {
        build(tableName, rowList);
    }

    @Override
    public void delete(String tableName, JSONArray rowList) {

    }

    /**
    *@Description: 根据报名信息查询订单号，学生电话，订单号，学生电话查询比订单创建时间小的最晚创建的资源
     * （或者已经关联该订单号的资源），欠费和缴费的订单才做处理。
    *@Param:
    *@return:
    *@Author: lzh
    *@date:
    */
    private void build(String tableName, JSONArray rowList){
        /* key :courseOrderId,value :studentPhoneNo*/
        Map<Long,String> orderIdMap=new HashMap<>();

        for (int i = 0; i < rowList.size(); i++) {
            try {
                JSONObject row = rowList.getJSONObject(i);
                StudentReg studentReg = row.toJavaObject(StudentReg.class);
                Long courseOrderId = studentReg.getCourseOrderId();
                if (!orderIdMap.containsKey(courseOrderId)) {
                    Student student = loadingCacheOfStudent.get(studentReg.getStudentId()).get();
                    orderIdMap.put(courseOrderId,student.getPhoneNo());
                }
            } catch (Exception e) {
                log.error("fill orderIdMap fail", e);
            }
        }
        for (Map.Entry<Long,String> entry:orderIdMap.entrySet()){
            try {
                Long courseOrderId=entry.getKey();
                CourseOrder courseOrder=courseOrderService.findById(courseOrderId);
                if (courseOrder.getChargingStatus()!=0){
                    List<CustomerResource> customerResourceList=null;
                    List<StudentReg> studentRegList=studentRegService.findByCourseOrderIds(Arrays.asList(courseOrderId));
                    Set<String> counselorIdSet=new TreeSet<>();
                    Set<String> counselorNameSet=new TreeSet<>();

                    for (StudentReg studentReg : studentRegList){
                        if (studentReg.getCounselorId()!=null){
                            counselorIdSet.add(studentReg.getCounselorId().toString());
                            counselorNameSet.add(StringUtils.defaultString(studentReg.getCounselorName()));
                        }
                    }
                    customerResourceList=customerResourceService.findCustomerResourceByCourseOrderId(courseOrderId);
                    if (Utils.checkListEmpty(customerResourceList)){
                        customerResourceList=new ArrayList<>();
                        String phone=entry.getValue();
                        List<CustomerResource> allCustomerResourceList=customerResourceService.findCustomerResourceByPhone(phone,courseOrder.getCreateTime());
                        Long maxTime=0l;
                        for (CustomerResource customerResource:allCustomerResourceList){
                            if (maxTime<=customerResource.getCreateTime().getTime()){
                                maxTime=customerResource.getCreateTime().getTime();
                            }
                        }
                        for (CustomerResource customerResource:allCustomerResourceList){
                            if (customerResource.getCreateTime().getTime()==maxTime){
                                customerResourceList.add(customerResource);
                            }
                        }
                    }
                    if (customerResourceList!=null){
                        for (CustomerResource customerResource:customerResourceList){
                            if (customerResource.getCourseOrderId()==null || courseOrderId.equals(customerResource.getCourseOrderId())){
                                CustomerResource update=new CustomerResource();
                                update.setCustomerResourceId(customerResource.getCustomerResourceId());
                                update.setCourseOrderId(courseOrderId);
                                update.setFirstRegAmount(courseOrder.getPaidAmount());
                                update.setFirstRegTime(courseOrder.getCreateTime());
                                update.setFirstRegNum(studentRegList.size());
                                update.setCounselorIds(StringUtils.join(counselorIdSet,","));
                                update.setCounselorNames(StringUtils.join(counselorNameSet,","));
                                update.setUpdateTime(TimeUtils.now());
                                customerResourceService.updateSelectiveById(update);
                            }
                        }
                    }


                }
            }catch (Exception e){
                log.error("deal orderIdMap fail", e);
            }

        }

    }
}
